<template>
	<view class="points-detail">

		<!-- 筛选栏 -->
		<view class="filter-tabs">
			<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
				@click="switchTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- 积分记录列表 -->
		<scroll-view scroll-y class="points-list">
			<block v-for="(monthGroup, month) in pointsData" :key="month">
				<!-- 月份标题 -->
				<view class="month-title">{{ month }}</view>

				<!-- 该月的积分记录 -->
				<view class="points-item" v-for="(item, index) in monthGroup" :key="index">
					<view class="item-left">
						<text class="item-title" v-if="item.title!=='5'">{{ item.title }}<text
								v-if="item.orderNo">(订单：{{ item.orderNo }})</text></text>
						<text class="item-title" v-if="item.title==='5'">{{ item.task }}<text
								v-if="item.orderNo">(订单：{{ item.orderNo }})</text></text>
						<text class="item-time">{{ item.time }}</text>
					</view>
					<view class="item-points" :class="item.points > 0 ? 'plus' : 'minus'">
						{{ item.points > 0 ? '+' : ''}}{{ item.points }}</view>
				</view>
			</block>
		</scroll-view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex"
	import {
		listPoints
	} from '@/api/points.js'
	export default {

		data() {
			return {
				tabs: ['全部', '获得', '消耗'],
				currentTab: 0,
				userId: this.$store.state.user.userId,
				rawPointsData: {}, // 存储原始格式化后的数据
				pointsData: {

				}
			}
		},
		onShow() {
			this.listPoints()
		},
		methods: {
			navigateBack() {
				uni.navigateBack()
			},
			switchTab(index) {
				this.currentTab = index
				this.filterPointsByTab()
			},

			listPoints() {
				listPoints({
					userId: this.userId
				}).then(res => {
					console.log(res)
					this.rawPointsData = this.formatPointsData(res.rows)
					this.filterPointsByTab()
				})
			},

			// 格式化积分数据，按月份分类
			formatPointsData(rawData) {
				if (!rawData || !Array.isArray(rawData)) {
					return {}
				}

				const monthGroups = {}

				rawData.forEach(item => {
					// 解析changeTime字段，假设格式为 "2025-04-15 09:13:00" 或类似格式
					const changeTime = item.changeTime
					if (!changeTime) return

					// 提取年月信息
					const date = new Date(changeTime)
					const year = date.getFullYear()
					const month = date.getMonth() + 1 // getMonth() 返回0-11，需要+1
					const monthKey = `${year}年${month.toString().padStart(2, '0')}月`

					// 格式化单条记录
					const formattedItem = {
						title: item.changeType, // 根据实际字段名调整
						task : item.task,
						time: this.formatDateTime(changeTime),
						points: parseInt(item.variablePoints || item.variablePoints || 0), // 根据实际字段名调整
						orderNo: item.orderNumber || item.orderNumber || '' // 如果有订单号
					}


					console.log(formattedItem)
					if (formattedItem.title === '1') {
						formattedItem.title = '订单奖励'
					} else if (formattedItem.title === '2') {
						formattedItem.title = '兑换消耗'
					} else if (formattedItem.title === '3') {
						formattedItem.title = '订单退款'
					} else if (formattedItem.title === '4') {
						formattedItem.title = '积分过期'
					} else if (item.title === '5') {
						formattedItem.title = formattedItem.task
					} else if (item.title === '6') {
						formattedItem.title = '手动调整'
					}

					// 按月份分组
					if (!monthGroups[monthKey]) {
						monthGroups[monthKey] = []
					}
					monthGroups[monthKey].push(formattedItem)
				})

				// 对每个月的数据按时间倒序排列
				Object.keys(monthGroups).forEach(month => {
					monthGroups[month].sort((a, b) => new Date(b.time) - new Date(a.time))
				})

				// 对月份进行排序（最新的月份在前）
				const sortedMonthGroups = {}
				Object.keys(monthGroups)
					.sort((a, b) => {
						// 解析年月进行比较
						const parseMonth = (monthStr) => {
							const match = monthStr.match(/(\d{4})年(\d{2})月/)
							if (match) {
								return new Date(parseInt(match[1]), parseInt(match[2]) - 1)
							}
							return new Date()
						}
						return parseMonth(b) - parseMonth(a)
					})
					.forEach(month => {
						sortedMonthGroups[month] = monthGroups[month]
					})

				return sortedMonthGroups
			},

			// 格式化日期时间显示
			formatDateTime(dateTimeStr) {
				if (!dateTimeStr) return ''

				const date = new Date(dateTimeStr)
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')

				return `${year}-${month}-${day} ${hours}:${minutes}`
			},

			// 根据tab筛选积分数据
			filterPointsByTab() {
				if (!this.rawPointsData || Object.keys(this.rawPointsData).length === 0) {
					this.pointsData = {}
					return
				}

				const filteredData = {}

				Object.keys(this.rawPointsData).forEach(month => {
					const monthData = this.rawPointsData[month]
					let filteredMonthData = []

					switch (this.currentTab) {
						case 0: // 全部
							filteredMonthData = monthData
							break
						case 1: // 获得
							filteredMonthData = monthData.filter(item => item.points > 0)
							break
						case 2: // 消耗
							filteredMonthData = monthData.filter(item => item.points < 0)
							break
						default:
							filteredMonthData = monthData
					}

					// 只有当该月有数据时才添加到结果中
					if (filteredMonthData.length > 0) {
						filteredData[month] = filteredMonthData
					}
				})

				this.pointsData = filteredData
			}

		}
	}
</script>

<style>
	.points-detail {
		min-height: 100vh;
		background: #f5f5f5;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 44px;
		padding: 0 15px;
		background: #fff;
		position: relative;
	}

	.back-icon,
	.right-icon {
		width: 24px;
		height: 24px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.title {
		flex: 1;
		text-align: center;
		font-size: 17px;
		font-weight: 500;
	}

	.filter-tabs {
		display: flex;
		background: #fff;
		padding: 12px 0;
		margin-bottom: 10px;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 14px;
		color: #666;
		position: relative;
	}

	.tab-item.active {
		color: #333;
		font-weight: 500;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: -8px;
		left: 50%;
		transform: translateX(-50%);
		width: 20px;
		height: 2px;
		background: #ff6b00;
		border-radius: 1px;
	}

	.points-list {
		height: calc(100vh - 100px);
	}

	.month-title {
		padding: 10px 15px;
		font-size: 14px;
		color: #000;
	}

	.points-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15px;
		background: #fff;
		margin-bottom: 10px;
		margin-left: 12px;
		margin-right: 12px;
	}

	.item-left {
		display: flex;
		flex-direction: column;
	}

	.item-title {
		font-size: 15px;
		color: #333;
		margin-bottom: 5px;
	}

	.item-time {
		font-size: 12px;
		color: #999;
	}

	.item-points {
		font-size: 16px;
		font-weight: 500;
	}

	.item-points.plus {
		color: #ff6b00;
	}

	.item-points.minus {
		color: #333;
	}
</style>